package com.example.http_url;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private WebView mwebView;
    //创建Task对象，Task有内存泄漏，避免内存泄漏，在destory的时候把对象concled
    private SendUrlTask msendurlTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mwebView = findViewById(R.id.webview);
        msendurlTask = new SendUrlTask("https://www.baidu.com");
        //执行
        msendurlTask.execute();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //防止内存泄漏
        if (msendurlTask != null)
        {
            msendurlTask.cancel(true);
        }

    }

    private class SendUrlTask extends AsyncTask<Void, Void, String>{

        public String murl;
        //需要传URL，创建构造方法
        public SendUrlTask(String url)
        {
            murl = url;
        }

        @Override
        protected String doInBackground(Void... voids) {
            //进行网络请求操作，后台线程执行
                return HttpUtil.sendUrl(murl);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mwebView.loadData(s, "text/html;charset=urf-8", null);
        }
    }
}
